local function currency_exists() end



minetest.register_privilege("currencies_admin", {  
    description = "It allows you to use /currencies"
})



ChatCmdBuilder.new("currencies", function(cmd)

    cmd:sub("add :plname :currency :amount:int", function(name, pl_name, currency, amount)
        if not currency_exists(pl_name, currency) then return end

        currencies.add(currency, pl_name, amount)
        currencies.print_msg(
            name, 
            "+ " .. amount .. ", ".. pl_name .. "'s " .. currency .. " balance: " .. currencies.get(currency, pl_name)
        )
    end)



    cmd:sub("sub :plname :currency :amount:int", function(name, pl_name, currency, amount)
        if not currency_exists(pl_name, currency) then return end

        currencies.sub(currency, pl_name, amount)
        currencies.print_msg(
            name, 
            "- " .. amount .. ", ".. pl_name .. "'s " .. currency .. " balance: " .. currencies.get(currency, pl_name)
        )
    end)


    cmd:sub("set :plname :currency :amount:int", function(name, pl_name, currency, amount)
        if not currency_exists(pl_name, currency) then return end

        currencies.set(currency, pl_name, amount)
        currencies.print_msg(name, pl_name .. "'s " .. currency .. " balance: " .. currencies.get(currency, pl_name))
    end)



    cmd:sub("balance :plname :currency", function(name, pl_name, currency)
        if not currency_exists(pl_name, currency) then return end

        currencies.print_msg(name, pl_name .. "'s " .. currency .. " balance: " .. currencies.get(currency, pl_name))
    end)



    cmd:sub("clearunregistered", function(name)
        currencies.remove_unregistered()

        currencies.print_msg(name, "Removed unregistered currencies from the database")
    end)



    cmd:sub("clearbalance :plname :currency", function(name, pl_name, currency)
        if not currency_exists(pl_name, currency) then return end

        currencies.clear_balance(currency, pl_name)

        currencies.print_msg(name, "Cleared " .. pl_name .. "'s " .. currency .. " balance")
    end)



    cmd:sub("clearbalance :plname", function(name, pl_name)
        currencies.clear_balance(nil, pl_name)

        currencies.print_msg(name, "Cleared " .. pl_name .. "'s balances")
    end)

end, {
    description = [[

    ADMIN COMMANDS
    (Use /help currencies to read it all)

    - balance <pl_name> <currency>
    - set <pl_name> <currency> <amount>
    - add <pl_name> <currency> <amount>
    - sub <pl_name> <currency> <amount>
    - clearunregistered: removes from the database every unregistered currency
    - clearbalance <pl_name> [currency]: if the currency isn't specified it'll reset each one of them
    ]],
    privs = {currencies_admin = true}
})



function currency_exists(pl_name, currency)
    if not currencies.exists(currency) then
        currencies.print_error(pl_name, "The " .. currency .. " currency doesn't exist")
        return false
    end

    return true
end
